package com.siyoumi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.entity.SysAccount;
import com.siyoumi.entity.SysRole;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mapper.SysAccountMapper;
import com.siyoumi.entity.SysAppRouter;
import com.siyoumi.component.XRedis;
import com.siyoumi.util.*;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


//t_s_account
@Slf4j
@Service
public class SysAccountService
        extends ServiceImplBase<SysAccountMapper, SysAccount> {
    @Override
    protected boolean softDelete() {
        return true;
    }

    static public SysAccountService getBean() {
        return XSpringContext.getBean(SysAccountService.class);
    }

    public String getUid(SysAccount entity) {
        if (this.isSuperAdmin(entity)) {
            return entity.getAcc_uid();
        }

        return XStr.concat(entity.getAcc_x_id(), "@", entity.getAcc_uid());
    }

    /**
     * 根据姓名获取帐号
     */
    public SysAccount getAccByUserName(String username) {
        QueryWrapper<SysAccount> query = q();
        //query.eq(SysAccount::getAcc_lock, 0);
        if (XStr.contains(username, "@")) {
            XLog.debug(this.getClass(), username + ":子账号登陆");

            String[] username_arr = username.split("@");
            String uid__super = username_arr[0];
            String uid = username_arr[1];

            query.eq("acc_x_id", uid__super)
                    .eq("acc_uid", uid);
        } else {
            XLog.debug(this.getClass(), username + ":超管登陆");

            query.eq("acc_role", "super_admin")
                    .eq("acc_uid", username);
        }

        return first(query);
    }

    /**
     * 根据姓名获取帐号
     */
    public SysAccount getAccByOpenid(String openid) {
        QueryWrapper<SysAccount> query = q();
        query.eq("acc_openid", openid);

        return first(query);
    }

    /**
     * 账号是否有效
     */
    public XReturn isValid(SysAccount entity) {
        if (entity == null) {
            return XReturn.getR(10110, "帐号不存在");
        }

        if (entity.getAcc_lock() == 1) {
            return XReturn.getR(10115, "帐号已停用");
        }

        if (entity.getAcc_lock_end_date().isAfter(XDate.now())) {
            String errmsg = XStr.concat("帐号被锁定，解锁时间：", XDate.toDateTimeString(entity.getAcc_lock_end_date()));
            XReturn r = XReturn.getR(10125, errmsg);
            r.setData("acc_lock_end_date", XDate.toDateTimeString(entity.getAcc_lock_end_date()));
            return r;
        }

        return XReturn.getR(0);
    }


    /**
     * 设置锁定时间
     *
     * @param entity 帐号
     * @param h      小时
     */
    public void setLockEnd(SysAccount entity, Integer h) {
        entity.setAcc_lock_end_date(XDate.now().plusHours(h));
        getBaseMapper().updateById(entity);
    }


    public Boolean isSpuerAdminOrDev(SysAccount entity) {
        if (isDev(entity)) {
            return true;
        }
        if (isSuperAdmin(entity)) {
            return true;
        }

        return false;
    }

    //超管
    public Boolean isSuperAdmin(SysAccount entity) {
        if ("super_admin".equals(entity.getAcc_role())) {
            return true;
        }

        return false;
    }

    //开发者
    public Boolean isDev(SysAccount entity) {
        if ("dev".equals(entity.getAcc_role())) {
            return true;
        }

        return false;
    }

    public Boolean isStore(SysAccount entity) {
        if ("store".equals(entity.getAcc_role())) {
            return true;
        }

        return false;
    }

    /**
     * 获取角色名称
     */
    public String getRoleName(SysAccount entity) {
        if (isSuperAdmin(entity)) {
            return "超级管理员";
        }
        if (isDev(entity)) {
            return "开发者";
        }

        SysRole entityRole = SysRoleService.getBean().getEntity(entity.getAcc_role());
        if (entityRole == null) {
            return entity.getAcc_role();
        }

        return entityRole.getRole_name();
    }


    /**
     * 根据token，获取对象
     */
    public SysAccount getSysAccountByToken() {
        String key = XHttpContext.getX() + "|getSysAccount";
        return XHttpContext.getAndSetData(key, item ->
        {
            XReturn tokenData = XHttpContext.getTokenData();
            if (tokenData == null) {
                return null;
            }
            String acc_id = tokenData.getData("acc_id");
            return getEntity(acc_id, true);
        });
    }


    /**
     * 检查帐号权限
     */
    public XReturn authCheck(SysAccount entity) {
        String appId = XHttpContext.getAppId();

        List<String> appIdsPass = authCheckPassApp();
        if (appIdsPass.contains(appId)) {
            return XReturn.getR(0, "通用应用不用检查权限");
        }

        if (isSpuerAdminOrDev(entity)) {
            //超管 开者发 判断app
            List<String> appIds = SysAppService.getBean().getAppIds(entity, true);
            if (!appIds.contains(appId)) {
                XReturn r = EnumSys.ADMIN_AUTH_APP_ERR.getR();
                r.setData("app_id", appId);
                return r;
            }
        } else {
            //其他判断角色权限
            String urlPath = XHttpContext.getUrlPath();
            List<String> paths = SysRoleService.getBean().getPathsByRole(entity.getAcc_role(), true);
            if (paths.contains(urlPath)) {
                XReturn r = EnumSys.ADMIN_AUTH_APP_ERR.getR();
                r.setData("url_path", urlPath);
                return r;
            }
        }

        return XReturn.getR(0);
    }

    public List<SysAppRouter> getListAppRouter(SysAccount entity) {
        SysAppRouterService app = SysAppRouterService.getBean();

        List<SysAppRouter> list = null;
        if (isSpuerAdminOrDev(entity) || isStore(entity)) {
            List<String> appIds = SysAppService.getBean().getAppIds(entity, true);
            list = app.getList(appIds, null);
        } else {
            List<String> pid = SysRoleService.getBean().mapper().getPidByRole(entity.getAcc_role());
            list = app.getList(null, pid);
        }

        return list;
    }

    static public String getDefPwd() {
        //当天日期，例：A20201119
        return "A" + XDate.format(XDate.today(), "yyyyMMdd");
//        return XDate.format(XDate.today(), "yyyyMMdd");
    }

    public XReturn resetPwd(String id, String newPwd) {
        if (XStr.isNullOrEmpty(newPwd)) {
            newPwd = getDefPwd();
        }
        SysAccount entityAcc = getById(id);

        String defPwd = XApp.encPwd(entityAcc.getX(), newPwd);
        UpdateChainWrapper<SysAccount> update = update();
        update.set("acc_pwd", defPwd)
                .eq(fdKey(), id)
                .update();
        String redisKey = XStr.concat("cache_model:SysAccount|", entityAcc.getX(), "|", id);
        log.debug("清徐缓存，key: {}", redisKey);
        XRedis.getBean().del(redisKey);

        XReturn r = XReturn.getR(0);
        r.setData("p", XStr.base64Enc(newPwd));
        return r;
    }

    /**
     * 重置，锁定时间
     *
     * @param id
     * @param newPwd
     */
    public XReturn resetLockDate(String id) {
        SysAccount entityUpdate = new SysAccount();
        entityUpdate.setAcc_id(id);
        entityUpdate.setAcc_lock_end_date(XDate.date2000());
        updateById(entityUpdate);

        delEntityCache(id);

        return EnumSys.OK.getR();
    }

    /**
     * 不需要检查的应用ID（通用应用）
     */
    protected static List<String> authCheckPassApp() {
        List<String> apps = new ArrayList<>();
        apps.add("z_common");
        apps.add("pwd");
        apps.add("wp_subscribemsg");
        apps.add("tmplmsg");
        apps.add("sys");
        return apps;
    }


}
